package chapter18;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/3/25 9:48
 */
public class ChannelCopy {
    private static final int BSIZE = 1024;

    public static void main(String[] args) throws IOException {
        if (args.length != 2) {
            System.out.println("args wrong");
            System.exit(1);
        }
        copy(args[0], args[1]);
    }

    public static void copy(String srcFile, String targetFile) throws IOException {
        FileChannel in = new FileInputStream(new File(srcFile).getAbsoluteFile()).getChannel();
        FileChannel out = new FileOutputStream(new File(targetFile).getAbsoluteFile()).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        while (in.read(buffer) != -1) {
            buffer.flip();  // prepare for writing
            out.write(buffer);
            buffer.clear(); //prepare for reading
        }
    }
}
